﻿using System;
using System.Collections.Generic;
using System.Text;
using Antu.Business.AbstractClass;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Windows.Forms;
using Antu.Business.Business;

namespace Antu.Business.Inheritance
{
    /// <!--
    /// 功能描述  : 物业资质申请审批数据操作
    /// 创建人  : LinJian
    /// 创建时间: 2007-07-09
    /// -->
    public class PropertyRequestDataOperation : AbstractDataOperation
    {
        /************** 物业企业资质申报流程说明 *******************
            WY_AWARD_INFO
            WY_COMPANY_INFO
            WY_COMPANY_BASIC
            WY_COMPANY_FEE
            WY_COMPANY_PERSON
            WY_ELEVATOR_INFO
            WY_EXPERT_INFO
            WY_MANAGE_ITEM
            WY_PERSON_COLLECT
            WY_PROSECUTION_INFO       
        
                    外网->Temp->内网	内网->Temp->外网
        CAN_SYNC	1->0	    0		1->0         0
        ********************************************************/

        #region 外网导出为临时文件
        /// <summary>
        /// 外网导出为临时文件 XML ,注意需要修改一些参数
        /// </summary>
        /// <returns></returns>
        public override DataSet WebToTempFile(string[] arrTables)
        {
            Database dbTemp = BasicOperate.CreateWebDataBase();
            DataSet dsReturn = new DataSet();

            string strSql = string.Empty;

            int maxValue = arrTables.Length;
            int curValue = 1;
            foreach (string strTable in arrTables)
            {
                Application.DoEvents();
                base.SetProgress(maxValue, curValue, "正在导出...当前表名：\"" + strTable + "\"");

                Application.DoEvents();
                strSql = string.Format(@"SELECT * FROM {0} W WHERE W.CAN_SYNC=1", strTable);

                DataSet dsSource = dbTemp.ExecuteDataSet(CommandType.Text, strSql);
                DataTable dtCopy = dsSource.Tables[0].Copy();

                if (dtCopy.Rows.Count > 0)//有数据才导出
                {
                    dtCopy.TableName = strTable;

                    //将取得的标志位重新设置值
                    this.ConvertDataCan_Dyn( ref dtCopy );
                    dsReturn.Tables.Add(dtCopy);

                    //更新状态位
                    strSql = string.Format(@"UPDATE {0} W SET W.CAN_SYNC=0", strTable);
                    dbTemp.ExecuteNonQuery(CommandType.Text, strSql);

                }
                curValue++;
            }
            return dsReturn;
        } 

        //做一下特殊处理
        private void ConvertDataCan_Dyn( ref DataTable dt )
        {
            for (int i = 0; i < dt.Rows.Count;i++ )
            {
                dt.Rows[i]["CAN_SYNC"] = 0;
            }        
        }
        #endregion

        #region 临时文件导入到内网
        /// <summary>
        /// 临时文件导入到内网
        /// </summary>
        /// <param name="arrTables"></param>
        /// <param name="dsSource"></param>
        public override void TempFileToInside(string[] arrTables, DataSet dsSource)
        {
            Database dbTemp = BasicOperate.CreateInsideDataBase();
            DbConnection conTemp = dbTemp.CreateConnection();

            //获取需要导入对象的所有表名
            List<string> lstNeedImportTables = ClsOracleSystemOperation.GetAllTablesName();

            //更新数据
            foreach (string strTable in arrTables)
            {
                if (dsSource.Tables.Contains(strTable))  //源数据中包含该表才操作
                {
                    DataTable dtSource = dsSource.Tables[strTable];
                    string strTempTable = dtSource.TableName.ToUpper();

                    if (lstNeedImportTables.Contains(strTempTable))
                    {
                        //删除本年的人员和项目信息
                        if (strTempTable.CompareTo("WY_MANAGE_ITEM") == 0 || strTempTable.CompareTo("WY_COMPANY_PERSON") == 0)
                        {
                            string strIdCollection = string.Empty;

                            foreach (DataRow drCopy in dtSource.Rows)
                            {
                                string strTemp = drCopy["company_id"].ToString();
                                if (strIdCollection.IndexOf(strTemp) == -1)
                                {
                                    if (!string.IsNullOrEmpty(strIdCollection))
                                    {
                                        strIdCollection += ",";
                                    }

                                    strIdCollection += string.Format("'{0}'", strTemp);
                                }
                            }

                            if (!string.IsNullOrEmpty(strIdCollection))
                            {
                                string strConditon = string.Format(" company_id in ({0})", strIdCollection);

                                ClsOracleSystemOperation.DeleteOneTableData(dbTemp, null, strTempTable, strConditon);
                            }
                        }
                        
                        //开始事务
                        conTemp.Open();
                        DbTransaction dbTrans = conTemp.BeginTransaction(); 

                        try
                        {
                            int maxValue = dtSource.Rows.Count;
                            int curValue = 1;

                            //行循环
                            foreach (DataRow drCopy in dtSource.Rows)
                            {
                                Application.DoEvents();
                                SetProgress(maxValue, curValue, "正在导入...当前表名：\"" + strTempTable + "\"  ID：" + drCopy["ID"].ToString());

                                string strKeyName = string.Empty;
                                string strKeyId = string.Empty;
                                if (drCopy.Table.Columns.Contains("ID"))
                                {
                                    strKeyName = "ID";
                                    strKeyId = drCopy["ID"].ToString();
                                }
                                else
                                {
                                    continue;
                                }

                                Application.DoEvents();

                                //求取指定的行
                                DataSet dsOneRow = ClsOracleSystemOperation.GetOneRowData(strTempTable, strKeyName, strKeyId);
                                DataTable dtTemp = dsOneRow.Tables[0];

                                //如果不存在就添加一行空的数据
                                if (dtTemp.Rows.Count == 0)
                                {
                                    dtTemp.Rows.Add(dtTemp.NewRow());
                                }
                                //只取第一行数据
                                DataRow drTemp = dtTemp.Rows[0];

                                if (strTempTable == "WY_COMPANY_BASIC")
                                {
                                    //获取表各列类型
                                    DataTable dtColTypeInfo = ClsOracleSystemOperation.GetFieldsNameOfTable(dbTemp, "WY_COMPANY_BASIC");
                                    drTemp = ClsFieldType.UpdateColumns(drTemp, drCopy, dtColTypeInfo);
                                }
                                else
                                {
                                    drTemp = ClsFieldType.UpdateColumns(drTemp, drCopy);
                                }

                                if (drTemp.RowState != DataRowState.Unchanged)
                                {
                                    DbCommand insertCommand = GetInsertCommand(dbTemp, DatabaseEngineType.OracleClient, strTempTable);
                                    DbCommand updateCommand = GetUpdateCommand(dbTemp, DatabaseEngineType.OracleClient, strTempTable, strKeyName);
                                    dbTemp.UpdateDataSet(dsOneRow, strTempTable, insertCommand, updateCommand, null, dbTrans);
                                }
                                curValue++;
                            }
                            dbTrans.Commit();
                        }
                        catch
                        {
                            dbTrans.Rollback();
                            throw;
                        }
                        finally
                        {
                            conTemp.Close();
                        }
                    }
                }
            }
        } 
        #endregion

        #region 内网导出为临时文件
        /// <summary>
        /// 内网导出为临时文件
        /// </summary>
        /// <returns></returns>
        public override DataSet InsideToTempFile(string[] arrTables)
        {
            Database dbTemp = BasicOperate.CreateInsideDataBase();
            DataSet dsReturn = new DataSet();

            string strSql = string.Empty;

            int maxValue = arrTables.Length;
            int curValue = 1;
            foreach (string strTable in arrTables)
            {
                Application.DoEvents();
                base.SetProgress(maxValue, curValue, "正在导出...当前表名：\"" + strTable + "\"");

                Application.DoEvents();
                strSql = string.Format(@"SELECT * FROM {0} W WHERE W.CAN_SYNC=1", strTable);

                DataSet dsSource = dbTemp.ExecuteDataSet(CommandType.Text, strSql);
                DataTable dtCopy = dsSource.Tables[0].Copy();

                if (dtCopy.Rows.Count > 0)//有数据才导出
                {
                    dtCopy.TableName = strTable;

                    //将取得的标志位重新设置值
                    this.ConvertDataCan_Dyn(ref dtCopy);
                    dsReturn.Tables.Add(dtCopy);

                    //更新状态位
                    strSql = string.Format(@"UPDATE {0} W SET W.CAN_SYNC=0", strTable);
                    dbTemp.ExecuteNonQuery(CommandType.Text, strSql);

                }
                curValue++;
            }
            return dsReturn;
        } 
        #endregion

        #region 临时文件导入到外网
        /// <summary>
        /// 临时文件导入到外网
        /// </summary>
        /// <returns></returns>
        public override void TempFileToWeb(string[] arrTables,DataSet dsSource)
        {
            Database dbTemp = BasicOperate.CreateWebDataBase();
            DbConnection conTemp = dbTemp.CreateConnection();

            //获取需要导入对象的所有表名
            List<string> lstNeedImportTables = ClsOracleSystemOperation.GetAllTablesName();

            //更新数据
            foreach (string strTable in arrTables)
            {
                if (dsSource.Tables.Contains(strTable))  //源数据中包含该表才操作
                {
                    DataTable dtSource = dsSource.Tables[strTable];
                    string strTempTable = dtSource.TableName.ToUpper();

                    if (lstNeedImportTables.Contains(strTempTable))
                    {
                        conTemp.Open();
                        DbTransaction dbTrans = conTemp.BeginTransaction(); //开始事务

                        try
                        {
                            int maxValue = dtSource.Rows.Count;
                            int curValue = 1;

                            //行循环
                            foreach (DataRow drCopy in dtSource.Rows)
                            {
                                Application.DoEvents();
                                SetProgress(maxValue, curValue, "正在导入...当前表名：\"" + strTempTable + "\"  ID：" + drCopy["ID"].ToString());

                                string strKeyName = string.Empty;
                                string strKeyId = string.Empty;
                                if (drCopy.Table.Columns.Contains("ID"))
                                {
                                    strKeyName = "ID";
                                    strKeyId = drCopy["ID"].ToString();
                                }
                                else
                                {
                                    continue;
                                }

                                Application.DoEvents();

                                //求取指定的行
                                DataSet dsOneRow = ClsOracleSystemOperation.GetOneRowData(strTempTable, strKeyName, strKeyId);
                                DataTable dtTemp = dsOneRow.Tables[0];

                                //如果不存在就添加一行空的数据
                                if (dtTemp.Rows.Count == 0)
                                {
                                    dtTemp.Rows.Add(dtTemp.NewRow());
                                }
                                //只取第一行数据
                                DataRow drTemp = dtTemp.Rows[0];

                                if (strTempTable == "WY_COMPANY_BASIC")
                                {
                                    //获取表各列类型
                                    DataTable dtColTypeInfo = ClsOracleSystemOperation.GetFieldsNameOfTable(dbTemp, "WY_COMPANY_BASIC");
                                    drTemp = ClsFieldType.UpdateColumns(drTemp, drCopy, dtColTypeInfo);
                                }
                                else
                                {
                                    drTemp = ClsFieldType.UpdateColumns(drTemp, drCopy);
                                }

                                if (drTemp.RowState != DataRowState.Unchanged)
                                {
                                    DbCommand insertCommand = GetInsertCommand(dbTemp, DatabaseEngineType.OracleClient, strTempTable);
                                    DbCommand updateCommand = GetUpdateCommand(dbTemp, DatabaseEngineType.OracleClient, strTempTable, strKeyName);
                                    dbTemp.UpdateDataSet(dsOneRow, strTempTable, insertCommand, updateCommand, null, dbTrans);
                                }
                                curValue++;
                            }
                            dbTrans.Commit();
                        }
                        catch
                        {
                            dbTrans.Rollback();
                            throw;
                        }
                        finally
                        {
                            conTemp.Close();
                        }
                    }
                }
            }
        } 
        #endregion
    }
}
